<template>
  <button
    class="btn-color-blue"
    size="mini"
    :disabled="isSending"
    :loading="isLoading"
    @click="handleSendMsg"
  >{{text}}</button>
</template>

<script>
import { SEND_MESSAGE_STORE } from '@/api'

export default {
  components: {},
  props: {
    phone: {
      type: String,
      required: true
    },
    type: {
      type: String,
      required: true,
      validator: function (val) {
        let list = [
          'REPAY_ERROR',
          'RESET_PASSWORD',
          'PHONE_LOGIN',
          'PHONE_CHECK'
        ]
        return list.includes(val)
      }
    }
  },
  data () {
    return {
      timer: 60,
      isSending: false,
      isLoading: false
    }
  },
  computed: {
    text () {
      if (this.isLoading) {
        return ''
      } else if (this.isSending) {
        return this.timer + 's'
      } else {
        return '发送验证码'
      }
    }
  },
  watch: {},
  created () {},
  mounted () {},
  onShow () {},
  methods: {
    handleSendMsg () {
      const vm = this

      if (!vm.phone) {
        vm.$toast('请输入手机号')
        return false
      } else if (!/^1[3456789]\d{9}$/.test(vm.phone)) {
        vm.$toast('手机号码格式有误')
        return false
      }

      vm.isLoading = true

      let params = {
        phone: vm.phone,
        providerId: vm.$store.state.account.providerId
      }

      SEND_MESSAGE_STORE(params, vm.type)
        .then(r => {
          vm.isLoading = false
          if (r.data.code === '0') {
            vm.timeCount()
            vm.$toast('发送成功，请注意查收')
          } else {
            vm.$toast(r.data.message)
          }
        })
        .catch(e => {
          vm.isLoading = false
          console.error(e)
        })
    },
    timeCount () {
      const vm = this

      vm.isSending = true
      let timer = setInterval(() => {
        vm.timer--
        if (vm.timer < 1) {
          clearInterval(timer)
          vm.isSending = false
          vm.timer = 60
        }
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.btn-color-blue {
  position: absolute;
  padding: 0;
  width: 80px;
  font-size: 12px;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  z-index: 10;
  background-color: #fff;
  border-radius: 25px;
  border: 1px solid #626efd;
  color: #626efd;
}
</style>
